package com.howie.parnote.jms;

import com.howie.parnote.dao.EmailRecordModuleMapper;
import com.howie.parnote.module.EmailRecordModule;
import com.howie.parnote.module.LoginInfoModule;
import com.howie.parnote.module.SharerModule;
import com.howie.parnote.util.DateUtil;
import com.howie.parnote.util.LogUtil;
import com.howie.parnote.util.security.DESCoder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;

/**
 * <p>Title: parnote</p>
 * <p>
 * Description: parnote
 * </p>
 *
 * @author huangyan
 *         Created by HY on 2015/4/18 0018.
 * @version v1.0.0
 */
@Service
public abstract class EmailMessageResolver implements MessageResolver {

	protected Logger logger = LogUtil.getLogger(this.getClass());

	@Autowired
	private EmailRecordModuleMapper emailRecordModuleMapper;

	@Override
	public String resolveMessage(Message message) throws JMSException {
		ObjectMessage objMessage = (ObjectMessage) message;
		if (logger.isDebugEnabled()) {
			logger.debug("EmailMessageResolver开始进行Message解析");
		}
		LoginInfoModule loginInfoModule = (LoginInfoModule) objMessage.getObject();
		SharerModule sharerModule = loginInfoModule.getSharer();
		StringBuilder urlParam = new StringBuilder();
		EmailRecordModule emailRecordModule = insertEmailRecord(sharerModule);
		try {
//			String uid = PasswordHash.createHash(sharerModule.getSharerId().toString());
			String sid = DESCoder.getHexEncodeId(sharerModule.getSharerId());
			String uid = sharerModule.getSharerId().toString();
			String eid = DESCoder.getHexEncodeId(emailRecordModule.getEmailRecordId());
			urlParam.append("sid=").append(sid).append("&uid=").append(uid).append("&eid=").append(eid);
		} catch (Exception e) {
			logger.error("email消息解析出现错误:" + e.getMessage(), e);
		}
		return urlParam.toString();
	}

	private EmailRecordModule insertEmailRecord(SharerModule sharerModule) {
		EmailRecordModule emailRecordModule = new EmailRecordModule();
		fillEmailType(emailRecordModule);
		emailRecordModule.setEmailStatus(EmailRecordModule.Status.UNCONFIRMED.getValue());
		emailRecordModule.setSendTime(DateUtil.getTimestamp());
		emailRecordModule.setSharerId(sharerModule.getSharerId());
		emailRecordModuleMapper.insert(emailRecordModule);
		return emailRecordModule;
	}

	protected abstract void fillEmailType(EmailRecordModule emailRecordModule);
}
